package Queue;

/**
 * Created by Administrator on 2017/10/14/014.
 */
public class CircularArrayQueue <T> implements Queue<T> {
    private final int DEFAULT_CAPACITY = 10;
    private int front,rear,count;
    private T[]queue;
    public CircularArrayQueue(){
        front = rear = count = 0;
        queue = (T[])(new Object[DEFAULT_CAPACITY]);
    }
    public void enqueue (T element){
        if(count == queue.length){
            expandCapacity();
            queue[rear] = element;
            rear = (rear+1) % queue.length;
            count++;
        }
    }
    public void expandCapacity()
    {
        T[]larger = (T[])(new Object[queue.length*2]);
        for(int index = 0;index<count;index++){
            larger[index] = queue[(front + index) % queue.length];
            front = 0;
            rear = count;
            queue = larger;
        }
    }
    public T dequeue() throws Exception {
        if (count == 0)
            throw new Exception("错误代码！");
        T a = queue[front];
        queue[front] = null;
        front = (front + 1) % queue.length;
        count--;
        return a;
    }


    public T first()throws Exception{
        if (count==0)
            throw new Exception ("错误代码");
        return queue[front];
    }

    public boolean isEmpty(){
        return(count==0);
    }
    public int size(){
        return count;
    }
    public String toString(){
        String result = "<top of Queue>\n";
        int math = 0;
        while (math<count)
        {
            if(queue[math]!=null)
            {
                result += queue[math].toString()+"\n";
            }
            math++;
        }
        return result + "<bottom of Queue>";
    }
}
